var workbook;

function uuid(){
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function (c) {
		var r =Math.random() * 16 | 0 ,
		 v = c == 'x' ? r: (r & 0x3|0x8);
		return v.toString(16);
	})
}


function uniqueArr(arr) { //数组对象去重

    let result = []; //中间数组
    let tempJson = {}; //缓存对象
    for(var i = 0; i < arr.length; i++) 
    {
        //如果在结果数组result中没有找到arr[i],则把arr[i]压入结果数组result中

        if (!tempJson[JSON.stringify(arr[i])]){
            result.push(arr[i]);
            tempJson[JSON.stringify(arr[i])]=true;
        } 
    }
    return result;
}


layui.use(['form'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.$;

    window.submitGoods = function(jsondata) {
        console.log("Debug jsondata:",jsondata);
        let sheetname = jsondata["excelsheet"];
        let jsonexcel = XLSX.utils.sheet_to_json(workbook.Sheets[sheetname]);
    
        for (let x = 0;x<jsonexcel.length;x++){
            if (Object.keys(jsonexcel[x]).length != Object.keys(jsonexcel[0]).length){
                jsonexcel.splice(x,1);
                continue;
            }
        }
    
        // 获取数据对照表 [{dbkey:username,impkey:收件人}]
        let mapdata=getMaplist();
        // 依照mapdata修改jsonexcel中的键，重组成resdata
        let resdata = new Array(jsonexcel.length).fill({});
    
        for (let y = 0; y < mapdata.length; y++) {//4
            // console.log("Debug mapdata:",mapdata);
            let a = mapdata[y].dbkey;
            let b = mapdata[y].impkey;
            let d = jsonexcel.map(function(item){
                return{
                    [a]:item[b]
                }
            });
    
            for (let zz in d){
                // if (Object.keys(d[zz]) == "userphone"){
                //     // console.log("Debug A!!",x,selectPhoneNum(d[zz].userphone));
                //     d[zz].userphone = selectPhoneNum(d[zz].userphone);
                // }
                resdata[zz] = {...resdata[zz],...d[zz]};
            }
    
        }
        let querydata = uniqueArr(resdata);   //去重
     
        for (let a in querydata){ //填充uid,dealer_id
            querydata[a].uid = uuid();
            querydata[a].dealer_id = jsondata.dealer_id;
        }
        // console.log("Debug querydata:",querydata);
        var wait = layer.load();
        // return resdata;
        // 调用接口/Member/add，添加数据
        $.ajax({
            url:"/Goods/add",
            type:"post",
            data:JSON.stringify(querydata),
            datatype:"json",
            success:(res)=>{
                layer.close(wait);
                var index = layer.alert(JSON.stringify(res), {
                    title: '最终的提交信息'
                }, function () {
    
                    // 关闭弹出层
                    layer.close(index);
    
                    var iframeIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(iframeIndex);
                });
            }
        })
    }
    
    window.getMaplist = function(){  //获取数据映射规则，对照
        let res=[];
    
        var objselect = document.getElementsByClassName('import');  
        
        for (x = 0; x < objselect.length; x++) {
            var dbkey = objselect[x].id;
            var impkey = $("#"+ dbkey +" option:selected").val();
            if (impkey != "default") {
                let c = new Object();
                c.dbkey = dbkey;
                c.impkey = impkey;
                res.push(c);
            }
        }
        return res;
    }
    var dealerSelect = document.getElementById("dealer_id");
    $.ajax({
        url:'/Dealer/list',
        type: "post",
        data: '{"page":1,"limit":15}',
        datatype:"json",
        success:function(data){
            // console.log("Debug data：",data);
            let optEle1 = document.createElement("option");
            optEle1.setAttribute("value","default");
            optEle1.appendChild(document.createTextNode("===选择经销商==="));
            dealerSelect.appendChild(optEle1);

            for (var x=0 ; x<data.data.length;x++){
                let optEle1 = document.createElement("option");
                optEle1.setAttribute("value",data.data[x].dealer_uid);
                optEle1.appendChild(document.createTextNode(data.data[x].dealer));
                dealerSelect.appendChild(optEle1);

            }
            layui.form.render("select");
        }
    });

    let jsonexcel;
    var selectObj = document.getElementById("sheetNames");

    // import-file变更，更新sheetNames下拉列表
    document.getElementById('import-file').addEventListener('change', function(e) {   //选择文件后执行
        // 清理下拉列表（sheetNames）
        $('#sheetNames option').remove();

        var optEle1 = document.createElement("option");
        optEle1.setAttribute("value","default");
        optEle1.appendChild(document.createTextNode("==选择sheetname=="));
        selectObj.appendChild(optEle1);

        let  files = e.target.files;
        if(files.length == 0) return;
        let  file = files[0];
        let  reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function(e) {   //处理load事件。读取操作完成时触发。
            let  data = e.target.result;
            
            workbook = XLSX.read(data, {type: 'binary'}); //XLSX：/xlsx.core.min.js 通过XLSX.read(data, {type: type})方法读取excel 后面介绍

            let  sheetNames = workbook.SheetNames; // 工作表名称集合
            for (i = 0;i<sheetNames.length;i++) {
                            
                // 填充sheetname下拉列表
                var optEle2 = document.createElement("option");
                optEle2.setAttribute("value",sheetNames[i]);
                optEle2.appendChild(document.createTextNode(sheetNames[i]));
                selectObj.appendChild(optEle2);
            }
            layui.form.render("select");

        };
    });

    form.on('select(sheetNames)', function(data){//动态调整表格中select的option
        // console.log("debug select:",data.value);
        // 清理表单中select的option
        $('.import option').remove();
   
        const sheet2JSONOpts = {
            defval:''
        }

        jsonexcel =  XLSX.utils.sheet_to_json(workbook.Sheets[data.value],sheet2JSONOpts);

        // console.log("debug Sheets:",workbook.Sheets[data.value]);
        // console.log("debug jsonexcel:",jsonexcel);
        //判断如果sheet页数据为空，则提示
        if (jsonexcel.length == 0) {
            alert("此页无数据，请选择其它sheet！");  
        }else{
            var title = [
                { "id": "goods_id", "view": "货品ID"},
                { "id": "goods", "view": "货品名称" },
                { "id": "goods_sku", "view": "规格名称"},
                { "id": "goods_code", "view": "商家编码" },
                { "id": "ware_house", "view": "发货仓库"},
                { "id": "supply_price", "view": "供货价" },
                { "id": "fixed_price", "view": "定价" },
                { "id": "remark", "view": "备注"}
            ];
            for (var x=0 ; x< title.length ; x++){
                var objselect = document.getElementById(title[x].id);
                var optEle = document.createElement("option");
                optEle.setAttribute("value", "default");
                optEle.appendChild(document.createTextNode("===选择列==="));
                objselect.appendChild(optEle);

                for (var y = 0 ; y < Object.keys(jsonexcel[0]).length ; y++){   //长度由sheet页内，列的数量决定
                    var optEle1 = document.createElement("option");
                    // 需要excel标题列名称
                    optEle1.setAttribute("value",Object.keys(jsonexcel[0])[y]);
                    optEle1.appendChild(document.createTextNode(Object.keys(jsonexcel[0])[y]));
                    objselect.appendChild(optEle1);
                }
            }
        }
        layui.form.render(null,'maprules');
    });


    //监听提交
    form.on('submit(saveBtn)', function (data) {
        submitGoods(data.field);
        return false;
    });

});